<template>
  <div class="register">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="register-from">
      <h2 class="register-title">注册页面</h2>
      <el-form-item label="用户名" prop="username">
        <el-input type="username" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model.number="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">注册</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getUserInfo, login} from "@/api/login";

export default {
name: "register",
  data() {
   /* var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };*/
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username:'',
        pass: '',
        checkPass: '',
        phone: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {//表示验证成功,valid 为 true 表示所有表单校验通过
          login(this.ruleForm.username, this.ruleForm.password).then(response => {
            const resp = response.data;
            console.log(resp, resp.flag, resp.data.token); //通过控制台可以看到打印的就是服务端返回的数据
            if (resp.flag) {//表示验证成功，不过由于服务端只会返回 true，但是也要判断下，因为实际开发中可能返回 false。
              //验证成功会返回一个 token，通过 token 去获取用户信息
              getUserInfo(resp.data.token).then(response => {//获取用户信息
                const respUser = response.data;
                if (respUser.flag)//用户信息获取成功
                {
                  alert('注册成功！');
                  console.log(respUser.data);//利用浏览器的本地存储保存 token 及用户信息
                  localStorage.setItem("mySystem-user", JSON.stringify(respUser.data)
                  );
                  //respUser.data 不转 json 格式不方便后面读取，因为是一个 Object 对象，如下图所示。所以外面包了一次格式转换函数。
                  localStorage.setItem("mySystem-token", resp.data.token);

                  //前往首页
                  this.$router.push("/login");
                } else//用户信息获取失败
                {
                  this.$message({
                    message: respUser.message,
                    type: "warning"
                  });
                }
              });
            }else{
              this.$message({
                message:response.message,
                type:'waring'
              })
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.register{
  /*绝对定位*/
  position: absolute;
  width: 100%;
  height: 100%;
  background-image:url("../../assets/login-bg.png");
}
.register-from{
  /*  绝对定位*/
  position: absolute;
  width:400px;
  background-color: white;
  /*margin: 160px auto;*/
  padding: 15px;
  border-radius:20px ;
  height: 400px;
  left:50%;
  top:50%;
  margin-left: -190px;
  margin-top: -250px;

}
.register-title{
  text-align: center;
  color:#606266;
}
</style>
